/*
 * File Name :  ProductWorkModel
 */
import Bb from 'backbone';
import Radio from 'backbone.radio';
import {
    formatAmount,
} from 'math.js';
import WorkItemCollection from './WorkItemCollection.js';
import BaseProductModel from './BaseProductModel.js';

const ProductWorkModel = BaseProductModel.extend({
    /* props spécifique à ce modèle */
    props: [
        'title',
        'items',
        'flat_cost',
    ],
    defaults() {
        return {};
    },
    validation: {
        title: {
            required: true,
            msg: "Veuillez saisir un titre"
        },
        items: function (value) {
            if (value.length === 0) {
                return "Veuillez saisir au moins un produit";
            }
        }
    },
    initialize: function () {
        ProductWorkModel.__super__.initialize.apply(this, arguments);
        this.facade = Radio.channel('facade');
        this.config = Radio.channel('config');
        this.is_complex = true;
        this.populate();
    },
    setupSyncEvents() {
        /* Launched when id is set */
        console.log("ProductWorkModel.onSetId");
        ProductWorkModel.__super__.setupSyncEvents.apply(this, arguments);
        this.stopListening(this.items);

        this.listenTo(this.items, 'saved', this.syncWithItems);
        this.listenTo(this.items, 'destroyed', this.syncWithItems);
    },
    populate() {
        console.log("ProductWorkModel.populate");
        if (this.has('items')) {
            this.items = new WorkItemCollection(this.get('items'));
        } else {
            this.items = new WorkItemCollection([]);
        }
        this.items.stopListening(this);
        this.items.listenTo(this, 'saved', this.items.syncAll.bind(this.items));
        this.items._parent = this;
        var this_ = this;
        this.items.url = function () {
            return this_.url() + '/' + "work_items";
        }
        this.items.syncAll();
    },
    syncWithItems() {
        this.set('items', this.items.toJSON());
        this.fetch();
    },
    supplier_ht_label() {
        return formatAmount(this.get('flat_cost'));
    },
    supplier_label() {
        return "-";
    },
    ht_label() {
        return formatAmount(this.get('ht'));
    },
    getIcons() {
        let icons = [];
        this.items.models.forEach(
            function (model) {
                let icon = model.getIcon();
                if (icon) {
                    icons.push(icon);
                }
            }
        );
        return [...new Set(icons)];
    },
    refreshWorkItems() {
        this.items.syncAll();
    },
});
/*
 * On complète les 'props' du BaseProductModel avec celle du ProductWorkModel
 */
ProductWorkModel.prototype.props = ProductWorkModel.prototype.props.concat(BaseProductModel.prototype.props);
_.extend(ProductWorkModel.prototype.validation, BaseProductModel.prototype.validation);
export default ProductWorkModel;